/**
 * 生成图片组件
 */
const GenerateImageView = {
    name: 'GenerateImageView',
    props: {
        settings: {
            type: Object,
            default: () => ({
                model: 'cogview-3-flash',
                size: '1024x1024'
            })
        }
    },
    data() {
        return {
            inputText: '',
            imageUrl: null,
            loading: false,
            imageLoaded: false,
            imageError: false,
            error: null
        };
    },
    methods: {
        async submit() {
            if (!this.inputText.trim()) {
                this.error = '请输入图片描述';
                return;
            }
            
            this.loading = true;
            this.error = null;
            this.imageUrl = null;
            this.imageLoaded = false;
            this.imageError = false;
            
            try {
                const result = await apiClient.generateImage(this.inputText.trim(), null, this.settings);
                
                if (result.success) {
                    let imageUrl = result.data.image_url;
                    
                    // 如果是相对路径，转换为完整URL
                    if (imageUrl.startsWith('/')) {
                        imageUrl = `${window.location.origin}${imageUrl}`;
                    }
                    
                    this.imageUrl = imageUrl;
                    
                    // 清空输入框
                    this.inputText = '';
                    this.$message.success('图片生成成功！');
                } else {
                    this.error = result.error || '生成图片失败';
                }
            } catch (error) {
                console.error('生成图片失败:', error);
                const errorInfo = window.ErrorHandler ? window.ErrorHandler.formatError(error) : { message: error.message || '未知错误' };
                this.error = errorInfo.message;
                if (errorInfo.suggestion) {
                    this.$message.warning(errorInfo.suggestion);
                }
            } finally {
                this.loading = false;
            }
        },
        onImageLoad() {
            this.imageLoaded = true;
            this.imageError = false;
        },
        onImageError() {
            this.imageError = true;
            this.imageLoaded = false;
            console.error('图片加载失败:', this.result);
        },
        downloadImage() {
            if (!this.imageUrl) return;
            
            // 创建一个临时的a标签进行下载
            const link = document.createElement('a');
            link.href = this.imageUrl;
            link.download = `generated-image-${Date.now()}.jpg`;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 如果是跨域图片，使用fetch下载
            fetch(this.imageUrl)
                .then(response => response.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `generated-image-${Date.now()}.jpg`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                })
                .catch(err => {
                console.error('下载失败:', err);
                alert('图片下载失败，请右键图片另存为');
                });
        }
    },
    watch: {
        imageUrl(newVal) {
            // 当imageUrl变化时重置加载状态
            if (newVal) {
                this.imageLoaded = false;
                this.imageError = false;
            }
        }
    },
    template: `
        <el-card shadow="hover" style="margin: 20px;">
            <div slot="header">
                <span style="font-size: 18px; font-weight: 600;">生成图片</span>
                <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">输入图片描述，AI将为您生成图片</p>
            </div>
            
            <el-input
                v-model="inputText"
                type="textarea"
                :rows="4"
                placeholder="请输入图片描述，例如：一只可爱的小猫坐在花园里"
            ></el-input>
            
            <div style="margin-top: 20px;">
                <el-button 
                    type="primary" 
                    @click="submit"
                    :loading="loading"
                    :disabled="!inputText.trim()"
                    icon="el-icon-magic-stick"
                    style="width: 100%;"
                >
                    {{ loading ? '生成中...' : '生成图片' }}
                </el-button>
            </div>

            <!-- 错误提示 -->
            <el-alert
                v-if="error"
                :title="error"
                type="error"
                :closable="true"
                @close="error = null"
                show-icon
                style="margin-top: 20px;"
            ></el-alert>

            <div v-if="imageUrl" style="margin-top: 20px;">
                <el-card shadow="never">
                    <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin: 0; font-size: 16px; font-weight: bold;">生成结果</h3>
                        <el-button 
                            type="primary" 
                            size="small" 
                            icon="el-icon-download"
                            @click="downloadImage"
                            :disabled="!imageLoaded"
                        >
                            下载图片
                        </el-button>
                    </div>
                    <!-- 图片加载中状态 -->
                    <div v-if="!imageLoaded && !imageError" style="text-align: center; padding: 40px; color: #909399;">
                        <i class="el-icon-loading" style="font-size: 32px;"></i>
                        <p style="margin-top: 10px;">图片加载中...</p>
                    </div>
                    <!-- 图片加载失败 -->
                    <div v-if="imageError" style="text-align: center; padding: 40px; color: #f56c6c;">
                        <i class="el-icon-picture-outline" style="font-size: 32px;"></i>
                        <p style="margin-top: 10px;">图片加载失败</p>
                        <p style="font-size: 12px; color: #909399; margin-top: 5px;">URL: {{ imageUrl }}</p>
                    </div>
                    <!-- 图片展示 -->
                    <div style="text-align: center; margin-top: 10px;">
                        <img 
                            :src="imageUrl" 
                            alt="Generated Image" 
                            style="max-width: 500px; max-height: 500px; border-radius: 4px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);"
                            :style="{display: imageLoaded ? 'inline-block' : 'none'}"
                            @load="onImageLoad"
                            @error="onImageError"
                            crossorigin="anonymous"
                        >
                    </div>
                </el-card>
            </div>
        </el-card>
    `
};

